//

#import "NT_MainViewController.h"
#import "NT_LeftTableView.h"
#import "NT_HomeCollectionViewCell.h"
#import "NT_SearchView.h"
#import "NT_MenuView.h"
#import "NT_NoteDetaiViewController.h"
#import "NT_HomeListCollectionViewCell.h"
#import "NT_SetViewController.h"
#import "NT_HistoryDeleteViewController.h"
#import "NT_CreatNoteViewController.h"
#import "NT_HomeReusableView.h"


@interface NT_MainViewController ()<UITableViewDelegate,UITableViewDataSource,NT_SearchViewDelegate,NT_LeftTableViewDelegate, NT_FootDeleteViewDelegate,NT_HomeListCollectionDelete,NT_HomeCollectionDelete>
{
    NSArray *_array;//menu数据
}
/** */
@property (nonatomic, strong) UITableView *collection;
/** */
@property (nonatomic, strong) NSMutableArray *dataArray;
/** 添加*/
@property (nonatomic, strong) NSMutableArray *addArray;
/** yes = list*/
@property (nonatomic, assign) BOOL  iscollect;
/** */
@property (nonatomic, strong) NT_CoreDataBase *data;
/** */
@property (nonatomic, strong) NT_CoreDataBase *deleData;
/** yes = bianji*/
@property (nonatomic, assign) BOOL  isEdit;
/** */
@property (nonatomic, strong) NT_FootDeleteView *deleView;
/** */
@property (nonatomic, strong) NT_MenuView *menu;
/** */
@property (nonatomic, strong) NT_SearchView *searchView;
/** */
@property (nonatomic, assign) BOOL  isshow;

@end

@implementation NT_MainViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (![[NSUserDefaults standardUserDefaults]objectForKey:@"sure"]) {
        //        [self saveFirstDatasss];
    }
    _data = [[NT_CoreDataBase alloc]initWithCoreData:@"Note" modelName:@"NoteData" success:^{} fail:^(NSError * _Nullable error) {}];
    _deleData = [[NT_CoreDataBase alloc]initWithCoreData:@"DeleData" modelName:@"NoteData" success:^{} fail:^(NSError * _Nullable error) {}];
    [self requestDatalllllll];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    _searchView.searchView.text = @"";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setTitle:@"All Note"];
    [self leftItem];
    //
    __weak typeof(self) weakSelf = self;
    [self nt_setupLeftAndRightwrurSetting:@"Add" block:^{
        //
        NT_CreatNoteViewController *vc = [[NT_CreatNoteViewController alloc]init];
        UINavigationController *nvc = [[UINavigationController alloc]initWithRootViewController:vc];
        [weakSelf presentViewController:nvc animated:YES completion:nil];
    }];
    //
    [self.view addSubview:self.collection];
}
//MARK:
- (void)leftItem {
    //
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 25, 25)];
    [button setImage:[UIImage imageNamed:@"list1"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(OnClick) forControlEvents:UIControlEventTouchUpInside];
    [button.titleLabel setFont:FontPFRegular(kRelativeWidth(15))];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = leftItem;
    //
    _searchView = [[NT_SearchView alloc]initWithFrame:CGRectMake(0, UI_NAV_BAR_HEIGHT, kMainScreenWidth, (40))];
    _searchView.backgroundColor = RGB(250, 250, 250);
    _searchView.delegate = self;
    [self.view addSubview:_searchView];
    
}
//MARK:左边v
- (void)OnClick {
    
    NT_LeftTableView *view = [[NT_LeftTableView alloc]init];
    view.delegate = self;
    [view showView];
}
/*
 //MARK:下啦
 - (void)menus {
 _menu = [[NT_MenuView alloc]init];
 if (_isEdit) {
 _menu.dataArray = @[@"Exit"];
 }else{
 if (_iscollect) {
 _menu.dataArray = @[@"Delete",@"List"];
 }else{
 _menu.dataArray = @[@"Delete",@"Collect"];
 }
 
 }
 [_menu showView];
 //
 __weak typeof(self) weakSelf = self;
 [_menu setIndexBlock:^(NSInteger index) {
 if (index == 1) {
 if (weakSelf.iscollect) {
 weakSelf.iscollect = NO;
 }else{
 weakSelf.iscollect = YES;
 }
 [weakSelf.collection reloadData];
 
 }else{
 NSLog(@"删除");
 weakSelf.isEdit =! weakSelf.isEdit;
 [weakSelf.collection reloadData];
 if (weakSelf.isEdit) {
 PostNotifition(@"Hidden");//TODO:底部view
 weakSelf.deleView = [[NT_FootDeleteView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(weakSelf.collection.frame), kMainScreenWidth, UI_TAB_BAR_HEIGHT)];
 weakSelf.deleView.delegate = weakSelf;
 [weakSelf.view addSubview:weakSelf.deleView];
 
 }else{
 PostNotifition(@"Appear");
 [weakSelf.deleView removeFromSuperview];
 }
 }
 }];
 }
 //MARK:listCell选中
 - (void)sendListCell:(NT_HomeListCollectionViewCell *)cell {
 if ([cell.model.status isEqual:@"1"]) {
 cell.model.status = @"";
 }else{
 cell.model.status = @"1";
 }
 [_collection reloadData];
 }
 //MARK:collectCell选中
 - (void)sendCollectCell:(NT_HomeCollectionViewCell *)cell {
 if ([cell.model.status  isEqual:@"1"]) {
 cell.model.status = @"";
 }else{
 cell.model.status = @"1";
 }
 [_collection reloadData];
 }
 
 //MARK:shanchu
 - (void)sendDeleteData {
 
 NSMutableArray *array = [NSMutableArray new];
 for (Note *model in _dataArray) {
 if ([model.status isEqual:@"1"]) {
 [array addObject:model];
 }
 }
 //cunchu
 for (Note *model in array) {
 NSMutableDictionary *dic = [NSMutableDictionary new];
 [dic setObject:@"2" forKey:@"id"];
 [dic setObject:model.date forKey:@"date"];
 [dic setObject:model.title forKey:@"title"];
 //
 [self.deleData ntInsertNewEntity:dic success:^{} fail:^(NSError * _Nullable error) {}];
 }
 //
 [self.data ntDeleteEntity:nil key:[NSString stringWithFormat:@"status = '%@'",@"1"] success:^{
 [self requestDatalllllll];
 
 } fail:^(NSError * _Nullable error) {}];
 
 }
 //MARK:退出
 - (void)exit {
 self.isEdit = NO;
 if (_iscollect) {
 _menu.dataArray = @[@"Delete",@"List"];
 }else{
 _menu.dataArray = @[@"Delete",@"Collect"];
 }
 [self.collection reloadData];
 PostNotifition(@"Appear");
 }
 //*/

//MARK:搜索
- (void)getTextFieldText:(NSString *)text {
    DLog(@"-search---%@",text);
    if (text.length <= 0) {
        [self requestDatalllllll];
        return;
    }
    [_data ntReadEntity:nil ascending:NO filterStr:[NSString stringWithFormat:@"title contains[cd] '%@'",text] success:^(NSArray * _Nonnull results) {
        if (!results) return ;
        self.dataArray = [results copy];
        [self.collection reloadData];
        
    } fail:^(NSError * _Nullable error) {}];
    
}
//MARK:点击leftCell
- (void)setCellIndex:(NSIndexPath *)indexPath text:(nonnull NSString *)text {
    if (indexPath.section == 0) {
        //
        if (indexPath.row == 1) {
            NT_HistoryDeleteViewController *vc = [[NT_HistoryDeleteViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        
    }else if (indexPath.section == 1){
        //
        _searchView.searchView.text = text;
        [_data ntReadEntity:nil ascending:NO filterStr:[NSString stringWithFormat:@"category = '%@'",text] success:^(NSArray * _Nonnull results) {
            if (!results) return ;
            self.dataArray = [results copy];
            [self.collection reloadData];
            
        } fail:^(NSError * _Nullable error) {}];
        
    }else{
        NT_SetViewController *vc = [[NT_SetViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    
}
//delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NT_HomeListCollectionViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([NT_HomeListCollectionViewCell class]) forIndexPath:indexPath];
    cell.model = _dataArray[indexPath.row];
    cell.delegate = self;
    if (_isEdit) {
        cell.selectButton.hidden = NO;
    }else
        cell.selectButton.hidden = YES;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kRelativeHeight(225);
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    NT_HomeReusableView *headerView = [[NT_HomeReusableView alloc]init];
    __weak typeof(self) weakSelf = self;
    headerView.advScrollView.clickItemOperationBlock = ^(NSInteger currentIndex) {
        //
        NT_CreatNoteViewController *vc = [[NT_CreatNoteViewController alloc]init];
        UINavigationController *nvc = [[UINavigationController alloc]initWithRootViewController:vc];
        [weakSelf presentViewController:nvc animated:YES completion:nil];
    };
    return headerView;
}
//*
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
// 定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

// 进入编辑模式，按下出现的编辑按钮后,进行删除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        Note *model = _dataArray[indexPath.section];
        //
        NSMutableDictionary *dic = [NSMutableDictionary new];
        [dic setObject:@"2" forKey:@"id"];
        [dic setObject:model.date forKey:@"date"];
        [dic setObject:model.title forKey:@"title"];
        //
        [self.deleData ntInsertNewEntity:dic success:^{} fail:^(NSError * _Nullable error) {}];
    
        __weak typeof(self) weakSelf = self;
        [self.data ntDeleteEntity:nil key:[NSString stringWithFormat:@"id = '%@'",model.id] success:^{
            [weakSelf requestDatalllllll];
            
        } fail:^(NSError * _Nullable error) {}];
        
    }
}

// 修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}
//*/
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated: YES];
    Note *model = _dataArray[indexPath.row];
    if (!_isEdit) {
        NT_NoteDetaiViewController *vc = [[NT_NoteDetaiViewController alloc]init];
        vc.dateStr = model.date;
        vc.titleStr = model.title;
        vc.imgs = (UIImage*)model.img;
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

//
#pragma mark ----------------- 懒加载 ----------------
- (UITableView *)collection {
    if (!_collection) {
        _collection = [[UITableView alloc]initWithFrame:CGRectMake(0, UI_NAV_BAR_HEIGHT, kMainScreenWidth, kMainScreenHeight) style:UITableViewStylePlain];
        _collection.dataSource = self;
        _collection.delegate   = self;
        _collection.tableFooterView = [UIView new];
        _collection.rowHeight  = kRelativeHeight(70);
        [_collection registerClass:[NT_HomeListCollectionViewCell class] forCellReuseIdentifier:NSStringFromClass([NT_HomeListCollectionViewCell class])];
    }
    return _collection;
}
- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray new];
    }
    return _dataArray;
}
- (NSMutableArray *)addArray {
    if (!_addArray) {
        _addArray = [NSMutableArray arrayWithObjects:@{@"category":@"travel",@"title":@"Walter's goal in life was to become a successful surgeon. First, though, he had to get through high school",@"date":@"2019-05-21 12:33",@"img":[UIImage imageNamed:@"header"],@"id":@"1111",},@{@"category":@"invest",@"title":@"Speaking and writing are different in many ways. Speech depends on sounds. Writing uses written symbols. Speech developed about 500 000 en211ago",@"date":@"2019-05-31 12:33",@"img":[UIImage imageNamed:@"header2"],@"id":@"2222",},@{@"title":@"Speaking and writing are different in many ways. Speech depends on sounds; writing, on the other hand, uses written symbols. Speech was developed about 500 000 years ago",@"date":@"2019-06-02 12:33",@"img":[UIImage imageNamed:@"header23"],@"id":@"3333",},@{@"title":@"In the movie, Robert Redford was a spy. He goes to his office where he found everybody dead. Other spies wanted to kill him, so he takes refuge with Julie Christie. At her house, he had waited for the heat to die down, but they come after him anyway.",@"date":@"2019-06-03 12:33",@"img":[UIImage imageNamed:@"header33"],@"id":@"4444",},@{@"title":@"Everybody looks for satisfaction in his life. They want to be happy. But if he seeks only pleasure in the short run, the person will soon run out of pleasure and life will catch up to him. They need to pursue the deeper pleasure of satisfaction in work and in relationships.",@"date":@"2019-06-04 18:33",@"img":[UIImage imageNamed:@"header33"],@"id":@"5555",},@{@"title":@"Now more than ever, parents need to be in touch with their children's activities because modern life has the tendency to cause cleavages in the family",@"date":@"2019-06-05 02:33",@"img":[UIImage imageNamed:@"header23"],@"id":@"6666",}, nil];
    }
    return _addArray;
}
//MARK:
- (void)requestDatalllllll {
    [_data ntReadEntity:nil ascending:NO filterStr:nil success:^(NSArray * _Nonnull results) {
        if (!results) return ;
        self.dataArray = [results copy];
        [self.collection reloadData];
        if (self.dataArray.count <= 0 && !self.isshow ) {
            self.isshow = YES;
            NT_CreatNoteViewController *vc = [[NT_CreatNoteViewController alloc]init];
            UINavigationController *nvc = [[UINavigationController alloc]initWithRootViewController:vc];
            [self presentViewController:nvc animated:YES completion:nil];
        }
        
    } fail:^(NSError * _Nullable error) {}];
}

//- (void)saveFirstDatasss {
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    [defaults setObject:@"yes" forKey:@"sure"];
//    [defaults synchronize];
//    for (NSDictionary *model in self.addArray) {
//        [_data ntInsertNewEntity:model success:^{} fail:^(NSError * _Nullable error) {}];
//    }
//
//}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (BOOL)nt_isShowLeft {
    return NO;
}

@end
